package me.flyray.bsin.server.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.constants.ResponseCode;
import me.flyray.bsin.context.BsinServiceContext;
import me.flyray.bsin.domain.entity.AgentCard;
import me.flyray.bsin.domain.entity.EmbeddingModel;
import me.flyray.bsin.domain.entity.KnowledgeBase;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.facade.service.KnowledgeBaseService;
import me.flyray.bsin.infrastructure.mapper.KnowledgeBaseMapper;
import me.flyray.bsin.mybatis.utils.Pagination;
import me.flyray.bsin.security.contex.LoginInfoContextHelper;
import me.flyray.bsin.security.domain.LoginUser;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.client.apache.dubbo.annotation.ShenyuDubboService;
import org.apache.shenyu.client.apidocs.annotations.ApiDoc;
import org.apache.shenyu.client.apidocs.annotations.ApiModule;
import org.apache.shenyu.client.dubbo.common.annotation.ShenyuDubboClient;
import org.springframework.ai.embedding.Embedding;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static me.flyray.bsin.constants.ResponseCode.*;

@Slf4j
@ShenyuDubboService(path = "/knowledgeBase", timeout = 6000)
@ApiModule(value = "knowledgeBase")
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

    @Autowired
    private KnowledgeBaseMapper knowledgeBaseMapper;

    @ApiDoc(desc = "add")
    @ShenyuDubboClient("/add")
    @Override
    public KnowledgeBase add(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        KnowledgeBase knowledgeBase = BsinServiceContext.getReqBodyDto(KnowledgeBase.class, requestMap);
        Optional.ofNullable(knowledgeBase.getTenantId())
                .or(() -> Optional.ofNullable(loginUser.getTenantId()))
                .ifPresentOrElse(
                        knowledgeBase::setTenantId,
                        () -> { throw new BusinessException(ResponseCode.TENANT_ID_NOT_ISNULL); }
                );
        knowledgeBaseMapper.insert(knowledgeBase);
        return knowledgeBase;
    }

    @ApiDoc(desc = "delete")
    @ShenyuDubboClient("/delete")
    @Override
    public void delete(Map<String, Object> requestMap) {
        String serialNo = MapUtils.getString(requestMap, "serialNo");
        if (knowledgeBaseMapper.deleteById(serialNo) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "edit")
    @ShenyuDubboClient("/edit")
    @Override
    public void edit(Map<String, Object> requestMap) {
        KnowledgeBase knowledgeBase = BsinServiceContext.getReqBodyDto(KnowledgeBase.class, requestMap);
        if (knowledgeBaseMapper.updateById(knowledgeBase) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "getDetail")
    @ShenyuDubboClient("/getDetail")
    @Override
    public KnowledgeBase getDetail(Map<String, Object> requestMap) throws Exception {
        String serialNo = MapUtils.getString(requestMap, "serialNo");
        KnowledgeBase knowledgeBase = knowledgeBaseMapper.selectById(serialNo);
        if (knowledgeBase == null) {
            throw new BusinessException(CONDITION_NOT_EXISTS);
        }
        return knowledgeBase;
    }

    @ApiDoc(desc = "getPageList")
    @ShenyuDubboClient("/getPageList")
    @Override
    public IPage<KnowledgeBase> getPageList(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        String type = MapUtils.getString(requestMap, "type");
        Object paginationObj =  requestMap.get("pagination");
        Pagination pagination = new Pagination();
        BeanUtil.copyProperties(paginationObj,pagination);

        Page<KnowledgeBase> page = new Page<>(pagination.getPageNum(),pagination.getPageSize());
        LambdaQueryWrapper<KnowledgeBase> warapper = new LambdaQueryWrapper<>();
        warapper.orderByDesc(KnowledgeBase::getCreateTime);
        warapper.eq(KnowledgeBase::getTenantId, loginUser.getTenantId());
        warapper.eq(KnowledgeBase::getType, type);
        warapper.eq(StringUtils.isNotBlank(loginUser.getMerchantNo()), KnowledgeBase::getMerchantNo, loginUser.getMerchantNo());
        IPage<KnowledgeBase> pageList = knowledgeBaseMapper.selectPage(page,warapper);
        return pageList;
    }

    @ApiDoc(desc = "getList")
    @ShenyuDubboClient("/getList")
    @Override
    public List<KnowledgeBase> getList(Map<String, Object> requestMap) {
        KnowledgeBase knowledgeBase = BsinServiceContext.getReqBodyDto(KnowledgeBase.class, requestMap);
        String tenantId = MapUtils.getString(requestMap, "tenantId");
        LambdaQueryWrapper<KnowledgeBase> warapper = new LambdaQueryWrapper<>();
        warapper.eq(KnowledgeBase::getTenantId, tenantId);
        warapper.eq(StringUtils.isNotBlank(knowledgeBase.getType()), KnowledgeBase::getType, knowledgeBase.getType());
        List<KnowledgeBase> knowledgeBaseList = knowledgeBaseMapper.selectList(warapper);
        return knowledgeBaseList;
    }

    @ApiDoc(desc = "getDefault")
    @ShenyuDubboClient("/getDefault")
    @Override
    public KnowledgeBase getDefault(Map<String, Object> requestMap) {
        return null;
    }

    @ApiDoc(desc = "setDefault")
    @ShenyuDubboClient("/setDefault")
    @Override
    public void setDefault(Map<String, Object> requestMap) {

    }

    @ApiDoc(desc = "retrieval")
    @ShenyuDubboClient("/retrieval")
    @Override
    public List<?> retrieval(Map<String, Object> requestMap) {
        return null;
    }

}
